package com.xoa.service.emergency;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.emergency.*;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.fixAssets.EduFixAssetsMapper;
import com.xoa.dao.hr.HrStaffInfoMapper;
import com.xoa.dao.hr.HrphotoMapper;
import com.xoa.dao.hr.hrEvaluate.HrEvaluateMapper;
import com.xoa.dao.position.PositionManagementMapper;
import com.xoa.dao.smsSettings.SmsSettingsMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.HrCode;
import com.xoa.model.common.HrCodeExample;
import com.xoa.model.common.SysCode;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.emergency.*;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.fixAssets.EduFixAssets;
import com.xoa.model.fixAssets.EduFixAssetsType;
import com.xoa.model.hr.HrStaffInfo;
import com.xoa.model.hr.HrphotoWithBLOBs;
import com.xoa.model.hr.hrEvaluate.HrEvaluate;
import com.xoa.model.position.UserJob;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.sms2.Sms2Priv;
import com.xoa.model.smsSettings.SmsSettings;
import com.xoa.model.users.OrgManage;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.service.smsDelivery.Sms2PrivService;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import com.xoa.util.sendUtil.HttpSend;
import com.xoa.util.sendUtil.send;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @作者 杨岩林
 * @创建日期 16:382019/10/12
 * @类介绍
 */
@Service
public class CrashDispatchService{

    @Resource
    private CrashDispatchMapper crashDispatchMapper;
    @Resource
    private CrashDispatchParentMapper crashDispatchParentMapper;
    @Autowired
    private EduFixAssetsMapper eduFixAssetsMapper;
    @Autowired
    private HrStaffInfoMapper hrStaffInfoMapper;
    @Resource
    private CheckAssetsNumMapper checkAssetsNumMapper;
    @Autowired
    private AttachmentMapper attachmentMapper;
    @Resource
    private HrphotoMapper hrphotoMapper;
    @Resource
    private HrCodeMapper hrCodeMapper;
    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private SysCodeMapper sysCodeMapper;
    @Resource
    private HrEvaluateMapper hrEvaluateMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Autowired
    private SmsService smsService;
    @Resource
    private PositionManagementMapper positionManagementMapper;
    @Resource
    private SysParaMapper sysParaMapper;
    @Resource
    private SmsSettingsMapper smsSettingsMapper;
    @Resource
    private UsersMapper usersMapper;

    public LimsJson insert(HttpServletRequest request ,CrashDispatchWithBLOBs crashDispatchWithBLOBs) {
        LimsJson toJson = new LimsJson(1, "err");
        try {
            int result = crashDispatchMapper.insertSelective(crashDispatchWithBLOBs);
            if (result > 0) {
                /**
                 * 增加救援事件后发送事务提醒和短信提醒
                 */
                //需要提醒的人员
                String strs = crashDispatchWithBLOBs.getRescueUser() + crashDispatchWithBLOBs.getReactionUser();
                AttendRemind(request,strs,"Uid",crashDispatchWithBLOBs.getCrasId());
                toJson.setCode(0);
                toJson.setMsg("新增成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    /**
     * 救援人员确认
     * @param request
     * @param type  0-不发送事务提醒，1-事务提醒参与救援人员
     * @param crasId
     * @return
     */
    public LimsJson confirmUsers(HttpServletRequest request ,String type,Integer crasId) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        LimsJson toJson = new LimsJson(1, "err");
        CrashDispatchWithBLOBs crashDispatchWithBLOBs = crashDispatchMapper.selectByPrimaryKey(crasId);
        //如果事件已确定，则无需重新确认
        if(!"1".equals(crashDispatchWithBLOBs.getEventState())){
            crashDispatchWithBLOBs.setConfirmUser(users.getUserId());
            crashDispatchWithBLOBs.setConfirmTime(new Date());
            crashDispatchWithBLOBs.setEventState("1");
            int i = crashDispatchMapper.updateByPrimaryKey(crashDispatchWithBLOBs);
            toJson.setCode(0);
            toJson.setMsg("true");
        }else{
            toJson.setCode(0);
            toJson.setMsg("救援人员已确认，无需重新确认。");
        }

        if(type !=null && "1".equals(type)){
            //应急救援人员
            String strs = crashDispatchWithBLOBs.getRescuePersons();
            AttendRemind(request,strs,"userId",crashDispatchWithBLOBs.getCrasId());
        }

        return toJson;
    }


    public LimsJson queryAll(Integer page, Integer limit) {
        LimsJson toJson = new LimsJson(1, "err");
        try {
            Map map = new HashMap();
            PageParams pageParams = new PageParams();
            pageParams.setUseFlag(true);
            pageParams.setPageSize(limit);
            pageParams.setPage(page);
            map.put("page", pageParams);
            List<CrashDispatchWithBLOBs> list = crashDispatchMapper.selectAll(map);
            if (list != null && list.size() > 0) {
                toJson.setCode(0);
                toJson.setMsg("查询成功");
                toJson.setCount(pageParams.getTotal());
                toJson.setData(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    public LimsJson update(HttpServletRequest request ,CrashDispatchWithBLOBs crashDispatchWithBLOBs) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        LimsJson toJson = new LimsJson(1, "err");
        try {
            crashDispatchWithBLOBs.setConfirmUser(users.getUserId());
            crashDispatchWithBLOBs.setConfirmTime(new Date());
            crashDispatchWithBLOBs.setEventState("0");
            int result = crashDispatchMapper.updateByPrimaryKeySelective(crashDispatchWithBLOBs);
            if (result > 0) {
//                //领导小组们
                String strs = crashDispatchWithBLOBs.getRescueUser() + crashDispatchWithBLOBs.getReactionUser();
                AttendRemind(request,strs,"Uid",crashDispatchWithBLOBs.getCrasId());
                toJson.setCode(0);
                toJson.setMsg("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    //type 1是人员详情查询 2是物资详情查询
    public LimsJson showDetails(Integer crasId,String type) {
        LimsJson toJson = new LimsJson(1, "err");
        CrashDispatchWithBLOBs crashDispatchWithBLOBs = crashDispatchMapper.selectByPrimaryKey(crasId);
        if(!StringUtils.checkNull(type)){
            if("1".equals(type)){
                String rescueUser = crashDispatchWithBLOBs.getRescueUser();
                String reactionUser = crashDispatchWithBLOBs.getReactionUser();
                String rescuePersons = crashDispatchWithBLOBs.getRescuePersons();
                Map<String,Object> maps= new HashMap<>();

                HrCode hrCode = new HrCode();
                hrCode.setParentNo("HR_STAFF_LICENSE1");
                hrCode.setCodeName("国际救援证件");
                hrCode = hrCodeMapper.getCodeNoByNameAndParentNo(hrCode);
                if(hrCode != null){
                    maps.put("licenseType",hrCode.getCodeNo());//只查找应急救援类型的证照信息
                    maps.put("status","2");//只查找已生效的信息
                    /**
                     * 领导小组
                     */
                    if(!StringUtils.checkNull(rescueUser)){
                        List<Users> listUser = usersMapper.getUsersByUids(rescueUser.split(","));
                        for(Users users:listUser){
                            maps.put("staffName",new String [] {users.getUserId()});
                            List<HrphotoWithBLOBs> list = hrphotoMapper.Allselect(maps);
                            UserJob userJob = positionManagementMapper.getUserjobId(users.getJobId());
                            users.setJobName(userJob != null ? userJob.getJobName() : "暂无岗位");
                            users.setHrphotoWithBLOBsList(list);
                        }
                        crashDispatchWithBLOBs.setRescueUserList(listUser);
                    }
                    /**
                     * 执行小组
                     */
                    if(!StringUtils.checkNull(reactionUser)){
                        List<Users> listUser = usersMapper.getUsersByUids(reactionUser.split(","));
                        for(Users users:listUser){
                            maps.put("staffName",new String [] {users.getUserId()});
                            List<HrphotoWithBLOBs> list = hrphotoMapper.Allselect(maps);
                            UserJob userJob = positionManagementMapper.getUserjobId(users.getJobId());
                            users.setJobName(userJob != null ? userJob.getJobName() : "暂无岗位");
                            users.setHrphotoWithBLOBsList(list);
                        }
                        crashDispatchWithBLOBs.setRescuePersonList(listUser);
                    }
                    /**
                     * 救援人员
                     */
                    if(!StringUtils.checkNull(rescuePersons)){
                        List<Users> listUser = usersMapper.getUsersByUserIds(rescuePersons.split(","));
                        for(Users users:listUser){
                            maps.put("staffName",new String [] {users.getUserId()});
                            List<HrphotoWithBLOBs> list = hrphotoMapper.Allselect(maps);
                            UserJob userJob = positionManagementMapper.getUserjobId(users.getJobId());
                            users.setJobName(userJob != null ? userJob.getJobName() : "暂无岗位");
                            users.setHrphotoWithBLOBsList(list);
                        }
                        crashDispatchWithBLOBs.setRescuePersonList(listUser);
                    }
                }


            }else if("2".equals(type)){
                String rescueEquipment = crashDispatchWithBLOBs.getRescueEquipment();
                if(!StringUtils.checkNull(rescueEquipment)){
                    List<EduFixAssets> fixAssetsList = new ArrayList<EduFixAssets>();
                    for (String id:rescueEquipment.split(",")) {
                        EduFixAssets eduFixAssets = eduFixAssetsMapper.selectById(id);
                        if(eduFixAssets != null){
                            fixAssetsList.add(eduFixAssets);
                        }
                    }
                    crashDispatchWithBLOBs.setRescueEquipmentList(fixAssetsList);
                }
            }

        }
        if (crashDispatchWithBLOBs != null) {
            toJson.setCode(0);
            toJson.setMsg("查询成功");
            toJson.setObj(crashDispatchWithBLOBs);
        }
        return toJson;
    }

    public LimsJson queryType() {
        LimsJson toJson = new LimsJson(1, "err");
        try {
            List<EduFixAssetsType> eduFixAssetsTypes = eduFixAssetsMapper.getFixAssetstypeName();
            if (eduFixAssetsTypes != null && eduFixAssetsTypes.size() > 0) {
                toJson.setCode(0);
                toJson.setMsg("查询成功");
                toJson.setData(eduFixAssetsTypes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    public LimsJson queryByType(Integer typeId,Integer page,Integer limit,String assetName,String info,String type) {
        LimsJson toJson = new LimsJson(1, "err");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("typeId",typeId);
        PageParams pageParams=new PageParams();
        if(page!=null&&limit!=null){
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            map.put("page",pageParams);
        }
        map.put("assetName",assetName);
        map.put("info",info);
        map.put("type",type);
        List<EduFixAssets> eduFixAssets = eduFixAssetsMapper.selectAssetsByType(map);
        for (int i = 0; i <eduFixAssets.size() ; i++) {
            EduFixAssets eduFixAssets1 = eduFixAssets.get(i);
            eduFixAssets1.setDeptName(eduFixAssets1.getDeptId() == 0 ? "": eduFixAssets1.getDeptName());
            SysCode location_address = sysCodeMapper.getSingleCode("LOCATION_ADDRESS",eduFixAssets1.getCurrutLocation());
            if(location_address!=null&&!StringUtils.checkNull(location_address.getCodeName())){
                eduFixAssets1.setCurrutLocation(location_address.getCodeName());
            } else{
                eduFixAssets1.setCurrutLocation("");
            }

//            关联查询物资调度信息 的最后一条记录(如果有记录说明调度过，资产只属于最后一个救援事件)
//            CpAssetDispatch cpAssetDispatch = cpAssetDispatchMapper.selectById(null,eduFixAssets1.getId());
//            if(cpAssetDispatch!=null){
//                eduFixAssets1.setCrasId(cpAssetDispatch.getCoverCrasId());
//                eduFixAssets1.setEventName(cpAssetDispatch.getCoverCrasName());
//            }
        }
        if (eduFixAssets != null && eduFixAssets.size() > 0) {
            toJson.setCode(0);
            toJson.setMsg("查询成功");
            toJson.setCount(pageParams.getTotal());
            toJson.setData(eduFixAssets);
        }else{
            toJson.setCode(1);
            toJson.setMsg("无数据");
        }
        return toJson;
    }

    public LimsJson queryUserType() {
        LimsJson toJson = new LimsJson(1, "err");
        try {
            List<String> types=hrStaffInfoMapper.queryWorkType();
            if(types!=null && types.size()>0){
                toJson.setCode(0);
                toJson.setMsg("查询成功");
                toJson.setData(types);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toJson;
    }

    public LimsJson queryUserByType(String typeName,Integer page,Integer limit,String staffName,Integer deptId ,String type) {
        LimsJson toJson = new LimsJson(1, "err");
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("typeName",typeName);
        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        map.put("page",pageParams);
        map.put("staffName",staffName);
        map.put("deptId",deptId);
        map.put("type",type);
        List<HrStaffInfo> hrStaffInfos=hrStaffInfoMapper.queryHrByType(map);
        Integer total = pageParams.getTotal();
        for (int i = 0; i < hrStaffInfos.size(); i++) {
            HrStaffInfo hrStaffInfo = hrStaffInfos.get(i);
            if(!StringUtils.checkNull(hrStaffInfo.getUserId())){
                map.put("userId", hrStaffInfo.getUserId());
                map.remove("deptId");
                List<HrEvaluate> hrEvaluates = hrEvaluateMapper.selectByHrEvaluate(map);
                if(hrEvaluates!=null&&hrEvaluates.size()>0){
                    hrStaffInfo.setEvaluate(hrEvaluates.get(0).getEvLevel());
                }
            }
            if(hrStaffInfo.getLocationAddress()!= null){
                SysCode sysCode = sysCodeMapper.selectById(hrStaffInfo.getLocationAddress());
                if(sysCode!=null){
                    hrStaffInfo.setLocationAddressName(sysCode.getCodeName());
                }
            }
            //  最后一次调拨记录
//            CpAssetDispatch cpAssetDispatch = cpAssetDispatchMapper.selectById(hrStaffInfo.getUserId(),null);
//            if(cpAssetDispatch!=null){
//                hrStaffInfo.setCrasId(cpAssetDispatch.getCoverCrasId());
//                hrStaffInfo.setEventName(cpAssetDispatch.getCoverCrasName());
//            }

        }
        if(hrStaffInfos!=null && hrStaffInfos.size()>0){
            toJson.setCode(0);
            toJson.setMsg("查询成功");
            toJson.setCount(total);
            toJson.setData(hrStaffInfos);
        }else{
            toJson.setMsg("暂无数据");
        }
        return toJson;
    }

    public int insertCheck(CheckAssetsNum checkAssetsNum) {
        return checkAssetsNumMapper.insertSelective(checkAssetsNum);
    }

    public LimsJson delete(Integer crasId) {
        LimsJson toJson = new LimsJson(1, "err");
        CrashDispatchParentWithBLOBs crashDispatchParentWithBLOBs = crashDispatchParentMapper.selectByCrasId(crasId);
        List<CrashDispatch>  list =  crashDispatchMapper.selectByPareId(crashDispatchParentWithBLOBs.getCrasPareId());
        if(list.size() <= 1){
            crashDispatchParentMapper.deleteByPrimaryKey(crashDispatchParentWithBLOBs.getCrasPareId());
        }
        int a=crashDispatchMapper.deleteByPrimaryKey(crasId);
        if(a>0){
            toJson.setCode(0);
            toJson.setMsg("删除成功");
        }
        return toJson;
    }

    public LimsJson toPDF(String htmlContent, HttpServletRequest request){
        LimsJson<Attachment> json = new LimsJson<Attachment>();

            // 设置pdf默认最大宽度
            Integer maxWidth = Integer.parseInt(request.getParameter("width"));
            Integer maxHeight = Integer.parseInt(request.getParameter("height"));

            // 文件存储头
            StringBuilder uploadHead = FileUploadUtil.getUploadHead();

            // 当前年月
            String ym = new SimpleDateFormat("yyMM").format(new Date());

            // 组织
            String company = "xoa" + (String) request.getSession().getAttribute("loginDateSouse");

            // 时间戳数字串
            String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));

            // 文件存储路径
            StringBuilder filePath = uploadHead.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append("crashDispatch").append(System.getProperty("file.separator")).
                    append(ym).append(System.getProperty("file.separator"));

            // 生成文件目录
            new File(uploadHead.toString()).mkdirs();

            // 获得原始文件名
            String htmlFileName = "救援信息.html";

            String newFileName = attachID + "." + htmlFileName.toString();

            // 生成文件
            String htmlFilePath = uploadHead.toString() + newFileName;
            File f = new File(htmlFilePath);

            try(OutputStreamWriter pw = new OutputStreamWriter(new FileOutputStream(htmlFilePath), "UTF-8");){
                if (!f.exists()) {
                    f.createNewFile();
                }
                htmlContent = htmlContent.replace("<>","<div style='display:none'>");
                htmlContent = htmlContent.replace("</>","</div>");
                pw.write("<html><head><meta charset=\"UTF-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"></head>");
                pw.write("<body>");
                pw.write(htmlContent);
                pw.write("</body></html>");
            }catch (Exception e){
                e.printStackTrace();
                L.e(e.getMessage());
            }

            // pdf文件名称
            String pdfFileName = attachID + "." + "救援信息.pdf";

            // pdf文件路径
            String pdfFilePath = filePath.append(pdfFileName).toString();

            // 生成PDF
            HtmlToPdfUtil.htmlToPDF(maxWidth,maxHeight,htmlFilePath,pdfFilePath,request);

            File pdfFile = new File(pdfFilePath);

            // 判断是否存在pdf文件
            if(pdfFile.exists()){

                //获得模块id
                byte mid = 0;

                // 保存进数据库
                Attachment attachment = new Attachment();
                attachment.setAttachId(attachID);
                attachment.setModule(mid);
                attachment.setAttachFile("救援信息.pdf");
                attachment.setAttachName("救援信息.pdf");
                attachment.setYm(ym);
                attachment.setAttachSign(new Long(0));
                attachment.setDelFlag((byte) 0);
                attachment.setPosition((byte) 2);
                attachment.setIsImage((byte) 0);
                attachment.setSize(Convert.convertFileSize(pdfFile.length()));
                attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                // 把附件信息存储进数据库中
                attachmentMapper.insertSelective(attachment);

                String attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=crashDispatch&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" +
                        "ATTACHMENT_NAME=" + attachment.getAttachName() + "&" + "FILESIZE=" + attachment.getFileSize();

                attachment.setAttUrl(attUrl);


                json.setObject(attachment);
                json.setMsg("ok");

            }


        return json;

    }

    public LimsJson<DepartmentExt> showDepts(Integer deptId){
        LimsJson<DepartmentExt> json = new LimsJson<DepartmentExt>();
        List<DepartmentExt> resultList = new ArrayList<>();
        List<Department> chDept;
        if(deptId==null||deptId==0){
            chDept = departmentMapper.getChDept(0);
        }else{
            chDept = departmentMapper.getChDept(deptId);
        }
        for (int i = 0; i < chDept.size(); i++) {
            DepartmentExt departmentExt = new DepartmentExt();
            departmentExt.setDeptName(chDept.get(i).getDeptName());
            departmentExt.setId(chDept.get(i).getDeptId());
            List<Department> chDept1 = departmentMapper.getChDept(chDept.get(i).getDeptId());
            if(chDept1!=null&&chDept1.size()>0){
                departmentExt.setIsLeaf(false);
            }
            resultList.add(departmentExt);
        }
        json.setData(resultList);
        json.setCode(0);
        return json;
    }

    public void AttendRemind(HttpServletRequest request ,String uIds,String type,final Integer crasId) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        final String FromId = users.getUserId();
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        if (uIds != null) {
        String[] strings = uIds.split(",");
        StringBuilder stringBuilderUserId = new StringBuilder();
        final StringBuffer mobileString = new StringBuffer();
        List<Users> list;
        if ("Uid".equals(type)) {
            list = usersMapper.getUsersByUids(strings);
        } else {
            list = usersMapper.getUsersByUserIds(strings);
        }
        for (Users user : list) {
            stringBuilderUserId.append(user.getUserId() + ",");
            String mobile = user.getMobilNo();
            if (mobile != null && !mobile.equals("")) {
                mobileString.append(mobile + ",");
            }
        }
        final String todoId = stringBuilderUserId.toString();
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
//                事务提醒
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("救援任务通知");
                sysCode.setParentNo("SMS_REMIND");
                SysCode sysCode1 = sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                if (sysCode1 != null) {
                    String codeType = sysCode1.getCodeNo();
                    SmsBody smsBody = new SmsBody();
                    smsBody.setSendTime((int) (new Date().getTime() / 1000)); //发送时间
                    smsBody.setSmsType(codeType);
                    smsBody.setIsAttach("0");
                    smsBody.setEditFlag("1");
                    smsBody.setFromId(FromId);//发送人USER_ID
                    smsBody.setContent("有紧急救援任务，请快速反应！");
                    smsBody.setRemindUrl("/crash/IntRescueDetail?crasId=" + crasId);
                    String title = "有紧急救援任务，请快速反应！";
                    String context = "有紧急救援任务，请快速反应！";
                    smsService.saveSms(smsBody, todoId, "1", "1", title, context, sqlType);
                }

//                发送短信=========
                StringBuffer mobile1;
                mobile1 = !"".equals(mobileString.toString()) ? mobileString.deleteCharAt(mobileString.length() - 1) : new StringBuffer();
                SysPara sysPara = sysParaMapper.querySysPara("MOBILE_SMS_SET");
                if (sysPara.getParaValue().equals("0") && !"".equals(mobile1.toString())) {
                    String stime = "";
                    Sms2Priv sms2Priv = new Sms2Priv();
                    sms2Priv.setStartTime(stime);
                    Map<String, String> maps = new HashMap<String, String>();
                    StringBuffer contextString = new StringBuffer("有紧急救援任务，请快速反应！");
                    List<SmsSettings> list = smsSettingsMapper.selectSmsSettings(new HashMap<String, Object>());
                    for (SmsSettings smsSettings : list) {
                        smsSettings.setSign("sign=" + smsSettings.getSign());
                        if ("湖北移动".equals(smsSettings.getName())) {
                            String url = smsSettings.getProtocol() + "://" + smsSettings.getHost() + "/" + smsSettings.getPort();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                            String[] p = smsSettings.getPwd().split("=");
                            String str1 = p[1] + sdf.format(new Date());
                            String str2 = Md5Util.getMd5String(str1);
                            maps.put("sign", str2);
                            maps.put("timestamp", sdf.format(new Date()));
                            String[] username1 = smsSettings.getUsername().split("=");
                            maps.put("userName", username1[1]);
                            maps.put("phones", mobile1.toString());
                            maps.put("msgContent", contextString.toString());
                            String[] extend1 = smsSettings.getExtend1().split("=");
                            maps.put("serviceCode", extend1[1]);
                            maps.put("mhtMsgIds", mobile1.toString());
                            maps.put("encoding", "utf-8");
                            maps.put("priority", "5");
                            String msgResult = HttpSend.sendPost(url, maps);
                            System.out.println("发送结果为：" + msgResult);
                        } else {
                            try {
                                send.doPost(mobileString, contextString, smsSettings.getProtocol(), smsSettings.getHost(), smsSettings.getPort(),
                                        smsSettings.getUsername(), smsSettings.getPwd(), smsSettings.getContentField(),
                                        smsSettings.getCode(), smsSettings.getMobile(), smsSettings.getTimeContent(), smsSettings.getSign(), smsSettings.getLocation(),
                                        smsSettings.getExtend1(), smsSettings.getExtend2(), smsSettings.getExtend3(), smsSettings.getExtend4(), smsSettings.getExtend5(),
                                        sms2Priv.getStartTime());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
    }
    }
}
